const canvas = document.getElementById("canvas1")
const ctx = canvas.getContext("2d")
const height = canvas.height
const width = canvas.width
const arrowAngle = 10 / 180 * Math.PI
const arrowLen = 20
const offset = 10
const color=["Red","Blue","Green","Orange","Aqua","BlueViolet","Brown","BurlyWood",
"CornflowerBlue","Crimson","DarkGreen","DarkOrange","DarkRed","Fuchsia"]
let colorNdx=0
let dim, space, zeroX, zeroY, zero
drawGrid()
function drawGrid(n = 20) {
	dim = n
	space = height / dim
	zero = [Math.floor(n * 0.4), Math.floor(n * 0.6)]
	zeroX = zero[0] * space
	zeroY = zero[1] * space
	ctx.setLineDash([5, 1])
	ctx.lineWidth = 1
	ctx.strokeStyle = ctx.fillStyle = "gray"
	for (let i = 0; i < dim; i++) {
		drawLine(0, i * space, width, i * space)
		drawLine(i * space, 0, i * space, height)
	}
	for (let i = 0; i <= dim; i += 2) {
		ctx.fillText(i - zero[0], i * space - offset, zeroY + offset)
		ctx.fillText(-i + zero[1], zeroX - offset, i * space)
	}
	ctx.setLineDash([])
	ctx.strokeStyle = ctx.fillStyle = "#5170b4ec"
	drawLine(0, zeroY, width, zeroY, true)
	drawLine(zeroX, height, zeroX, 0, true)
	ctx.strokeStyle = ctx.fillStyle = color[colorNdx]
	ctx.font = "15 serif"
}
function drawLine(x0, y0, x1, y1, arrow = false) {
	ctx.beginPath()
	ctx.moveTo(x0, y0)
	ctx.lineTo(x1, y1)
	ctx.stroke()
	if (arrow) {
		ctx.fillStyle = ctx.strokeStyle
		let ang = (Math.atan2(y0 - y1, x0 - x1) + (2 * Math.PI)) % (2 * Math.PI)
		let a1 = ang + arrowAngle, a2 = ang - arrowAngle
		let arrX1 = x1 + arrowLen * Math.cos(a1), arrY1 = y1 + arrowLen * Math.sin(a1)
		let arrX2 = x1 + arrowLen * Math.cos(a2), arrY2 = y1 + arrowLen * Math.sin(a2)
		ctx.beginPath()
		ctx.moveTo(x1, y1)
		ctx.lineTo(arrX1, arrY1)
		ctx.lineTo(arrX2, arrY2)
		ctx.fill()
	}
}
function changeColor(){
	colorNdx++
	ctx.fillStyle = ctx.strokeStyle= color[colorNdx]
}
function drawVec(p1, p2 = [0, 0], arrow = true, text = "") {
	let x1 = p1[0] * space + zeroX, y1 = -p1[1] * space + zeroY
	let x2 = p2[0] * space + zeroX, y2 = -p2[1] * space + zeroY
	if (arguments.length == 1)
		drawLine(zeroX, zeroY, x1, y1, arrow)
	else
		drawLine(x1, y1, x2, y2, arrow)
	if (text)
		ctx.fillText(text, x2 + 0.5 * offset, y2 - 0.5 * offset)

}
